package com.beerandjesus.sportofkings.handicapper;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.beerandjesus.sportofkings.handicapper.app.CardAnalyzerException;
import com.beerandjesus.sportofkings.handicapper.app.JockeyRatingDatabaseBuilder;
import com.beerandjesus.sportofkings.handicapper.model.brisnet.singlefile.CardVOImpl;
import com.beerandjesus.sportofkings.handicapper.dao.Database;

/**
 * Utility for adding jockey ratings to the jockey rating database
 *
 */
public class JockeyDatabaseUtil {
	private ApplicationContext context;
    private String filePath;
    private JockeyRatingDatabaseBuilder builder;
    private CardVOImpl card;
    private Database database;

    public static void main( String[] args ) {
        JockeyDatabaseUtil main = new JockeyDatabaseUtil();
        if (args == null || args.length < 1 || args.length > 2) {
            return;
        }
        ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"spring-config.xml",
        "applicationContext-handicapper-jar.xml"});
        main.setApplicationContext(context);
        main.setFilePath(args[0]);
        if (args.length == 2) {
            if (args[1].equals("rebuild")) {
                main.rebuild();
                return;
            } else {
                return;
            }
        }
        main.execute();
    }

    public void rebuild() {
        init();
        database.rebuildJockeyRatingDatabase();
        addAllJockeys();

    }

    public void execute() {
        init();
        addAllJockeys();
    }

    private void addAllJockeys() {
        try {
            builder.addAllJockeys(card);
        } catch (CardAnalyzerException e) {
            e.printStackTrace();
            return;
        }
        int dbCount = database.getJockeyPerformanceDatabaseRowCount();
        System.out.println("Jockey performances added; database row count is " + dbCount);
    }

    private void init() {
        builder = (JockeyRatingDatabaseBuilder) context.getBean("jockeyPerformanceDatabaseBuilder");
        card = new CardVOImpl();
        card.setFilePath(getFilePath());
        database = (Database) context.getBean("database");
    }

    public void setApplicationContext(ApplicationContext context) {
    	this.context = context;
    }

    public ApplicationContext getApplicationContext() {
    	return context;
    }

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }
}
